package com.moter.demo01.juc.alllocks.spinlock;

import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) {
        Products products = new Products();
        SpinLock pro = new SpinLock();
        SpinLock com = new SpinLock();

//            普通自旋锁
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                com.lock();
                try {
                    new MyConsumer().accept(products);
                    System.out.println(Thread.currentThread().getName()+"\t消费商品");
                }finally {
                    com.unLock();
                }
            },"consumer:"+i).start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                pro.lock();
                try {
                    Products.Product product = new MyProvider().get();
                    products.getQueue().offer(product,5,TimeUnit.SECONDS);
                    System.out.println(Thread.currentThread().getName()+"\t放如商品\t"+product);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                } finally {
                    pro.unLock();
                }
            },"provider:"+i).start();
        }
        //适应性自旋锁
//        for (int i = 0; i < 10; i++) {
//            new Thread(() -> {
//                try {
//                    pro.adaptiveLock();
//                    Products.Product product = new MyProvider().get();
//                    products.getQueue().offer(product,5,TimeUnit.SECONDS));
//                    System.out.println(Thread.currentThread().getName() + "\t放如商品\t" + product);
//                } catch (RuntimeException e) {
//                    System.out.println(e.getMessage());
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                } finally {
//                    pro.unLock();
//                }
//            }, "provider:" + i).start();
//        }
//        for (int i = 0; i < 10; i++) {
//            new Thread(() -> {
//
//                try {
//                    com.adaptiveLock();
//                    new MyConsumer().accept(products);
//                    System.out.println(Thread.currentThread().getName() + "\t消费商品");
//                } catch (RuntimeException e) {
//                    System.out.println(e.getMessage());
//                } finally {
//                    com.unLock();
//                }
//            }, "consumer:" + i).start();
//        }


        //main线程等待所有线程执行完毕
        while (Thread.activeCount() > 2) {//main,gc
        }
        System.out.println(products.getQueue().size());
    }
}
